package com.wrh.demo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wrh.springboot.restwrap.RestWrapIgnore;
import com.wrh.springboot.restwrap.compress.GzipUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;


/**
 * @author wrh
 */
@RestController
@RequestMapping("compress")
public class CompressController {

    @Autowired
    private ObjectMapper objectMapper;

    @GetMapping("srcArrayWithRestWrap")
    public Object srcArrayWithRestWrap() {
        return generateGrid();
    }

    @RestWrapIgnore
    @GetMapping("srcArray")
    public Object srcArray() {
        return generateGrid();
    }


    @RestWrapIgnore
    @GetMapping("gzipArray")
    public Object gzipArray() throws JsonProcessingException {
        return GzipUtil.compressByStr(objectMapper.writeValueAsString(generateGrid()));
    }

    @RestWrapIgnore
    @GetMapping("srcJson")
    public Object srcJson() throws IOException {
        return getJson();
    }

    @RestWrapIgnore
    @GetMapping("gzipJson")
    public Object gzipJson() throws IOException {
        return GzipUtil.compressByStr(getJson());
    }


    private double[][] generateGrid(){
        int len1 = 500;
        int len2 = 300;
        double[][] grid = new double[len1][len2];
        for (int i = 0; i < len1; i++) {
            for (int j = 0; j < len2; j++) {
                grid[i][j] = Math.random();
            }
        }
        return grid;
    }


    private String getJson() throws IOException {
        InputStream ins = this.getClass().getClassLoader().getResourceAsStream("public/rain.json");
        assert ins != null;
        return new String(new byte[ins.available()]);
    }

}


